<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-row>
          <el-button type="success" @click="handleCreate">新增</el-button>
          <el-form
            :inline="true"
            :model="listQuery"
            ref="listQuery"
            class="demo-form-inline"
          >
            <el-form-item label="">
              <el-input
                type="text"
                v-model="listQuery.search"
                clearable
                placeholder="请输入角色名称"
              ></el-input>
            </el-form-item>
            <el-form-item label="">
              <el-select
                filterable
                v-model="listQuery.status"
                clearable
                placeholder="请选择状态(默认全部)"
              >
                <el-option
                  v-for="item in statusOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="searchSubmit">查询</el-button>
              <el-button type="primary" @click="resetSubmit">重置</el-button>
            </el-form-item>
          </el-form>
        </el-row>
      </div>
      <div class="item">
        <el-table
          v-loading="listLoading"
          ref="dataList"
          :data="menuList"
          style="width:100%;margin-bottom: 20px;"
          row-key="id"
          border
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        >
          <!-- <el-table-column type="selection"></el-table-column> -->
          <el-table-column prop="role_id" label="角色ID"></el-table-column>
          <el-table-column prop="role_name" label="角色名称"></el-table-column>
          <el-table-column prop="add_time" label="创建时间"></el-table-column>
          <el-table-column prop="status" label="状态">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.status === 1" type="success">正常</el-tag>
              <el-tag v-if="scope.row.status === 2" type="danger">禁用</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="role_memo" label="角色备注"></el-table-column>
          <el-table-column prop="admin" label="角色用户">
            <template slot-scope="scope">
              <span v-for="item in scope.row.admin" :key="item['admin_id']">{{
                item.admin_name
              }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180px">
            <template slot-scope="scope">
              <el-button
                type="primary"
                size="mini"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                plain
                >编辑
              </el-button>
              <el-button
                type="danger"
                size="mini"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                plain
                >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <cus-pagination
          :total="total"
          :page.sync="listQuery.page"
          :limit.sync="listQuery.perPage"
          @pagination="getList"
        />
      </div>
    </el-card>
    <!-- 删除弹框 -->
    <el-dialog
      title="确定删除吗?"
      :visible.sync="deleteDialogVisible"
      width="435px"
    >
      <span style=""
        ><em style="font-style:normal;color:red">删除后不可恢复</em
        >，你还要继续吗？</span
      >
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmDelete">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 新增弹出框 -->
    <el-dialog
      v-dialogDrag
      :title="titleMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
    >
      <el-form
        v-loading="addEditVisible"
        :model="editRulesForm"
        :rules="editRulesFormRules"
        ref="editRulesForm"
        label-width="120px"
        class="demo-ruleForm"
      >
        <el-form-item label="角色名称" prop="role_name">
          <el-input
            v-model="editRulesForm.role_name"
            placeholder="请输入角色名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="role_memo">
          <el-input
            type="textarea"
            v-model="editRulesForm.role_memo"
          ></el-input>
        </el-form-item>
        <el-form-item label="角色状态" prop="status">
          <el-select
            filterable
            v-model="editRulesForm.status"
            placeholder="请选择状态"
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="角色权限" prop="permissionArr_str">
          <el-button type="primary" plain @click="toggleCheckPermission"
            >全选</el-button
          >
          <!-- data 绑定所有的权限菜单  node-key 每个树节点用来作为唯一标识的属性  default-checked-keys 默认勾选的节点的 key 的数组 -->
          <el-tree
            ref="permissionTree"
            :data="permissionList"
            show-checkbox
            node-key="menu_id"
            :default-checked-keys="editRulesForm.permissionArr"
            @check-change="handleCheckPermissionChange"
            :props="defaultProps"
          >
          </el-tree>
        </el-form-item>
        <el-form-item label="角色菜单" prop="menuArr_str">
          <el-button type="primary" plain @click="toggleCheckMenu"
            >全选</el-button
          >

          <el-tree
            ref="menuTree"
            v-model="editRulesForm.menuArr"
            :data="menuArrList"
            show-checkbox
            check-strictly
            node-key="menu_id"
            :default-checked-keys="editRulesForm.menuArr"
            @check-change="handleCheckMenuChange"
            :props="defaultProps"
          >
          </el-tree>
        </el-form-item>
        <el-form-item>
          <el-button @click="dialogFormVisible = false">返回</el-button>
          <el-button type="primary" @click="confirmSubmit('editRulesForm')"
            >提交</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>

    <role-create ref="role_create" />
  </div>
</template>

<script>
import RoleCreate from "@/views/config/components/RoleCreater";

import {
  listData,
  getPermission,
  getMenu,
  getRoleDetail,
  postAddData,
  postEditData,
  deleteData
} from "@/api/config/role";

export default {
  components: { RoleCreate },
  computed: {
    roleCreateIns() {
      return this.$refs["role_create"];
    }
  },
  data() {
    return {
      // 另存一个当前行的id
      row_id: 0,
      //
      addEditVisible: false,
      // 全选权限控制开关
      checkPermission: false,
      // 全选菜单控制开关
      checkMenu: false,
      // 树节点
      defaultProps: {
        children: "children",
        label: "menu_name"
      },
      // 表单验证
      editRulesFormRules: {
        role_name: [
          { required: true, message: "请输入角色名称", trigger: "blur" }
        ],
        role_memo: [
          {
            max: 200,
            message: "长度最多200个字符",
            trigger: "blur",
            required: false
          }
        ],
        status: [
          { required: true, message: "请选择角色状态", trigger: "change" }
        ],
        permissionArr_str: [
          { required: true, message: "请选择角色权限", trigger: "change" }
        ],
        menuArr_str: [
          { required: true, message: "请选择角色菜单", trigger: "change" }
        ]
      },
      dialogStatus: "",
      // dialog的头部信息
      titleMap: {
        update: "编辑",
        create: "新增"
      },
      // 新增编辑弹出框
      dialogFormVisible: false,
      // 新增传入表单  需要去掉menuArr permissionArr
      editRulesForm: {
        role_name: undefined,
        role_memo: undefined,
        status: undefined,
        menuArr: [],
        permissionArr: [],
        menuArr_str: undefined,
        permissionArr_str: undefined
      },
      // 权限列表
      permissionList: [],
      // 菜单列表
      menuArrList: [],
      deleteDialogVisible: false,
      listLoading: false,
      menuList: [],
      limitList: [],
      listQuery: {
        page: 1,
        perpage: 10,
        searchSubmit: undefined,
        status: undefined
      },
      statusOptions: [
        {
          value: 1,
          label: "正常"
        },
        {
          value: 2,
          label: "禁用"
        }
      ],
      total: 0,
      dataIds: undefined
    };
  },
  created() {
    this.getList();
    this.getPermissionArr();
    this.getMenuArr();
  },
  methods: {
    getList() {
      this.listLoading = true;
      listData(this.listQuery).then(({ data: { list, meta } }) => {
        this.menuList = list;
        this.total = meta.total;
        this.listLoading = false;
      });
    },
    // 点击查询
    searchSubmit() {
      this.listQuery.page = 1;
      this.getList();
    },
    // 点击重置
    resetSubmit() {
      this.listQuery.page = 1;
      this.listQuery.perpage = 10;
      this.listQuery.search = undefined;
      this.listQuery.status = undefined;
    },

    // 点击新增
    handleCreate() {
      this.resetForm();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs.menuTree.setCheckedKeys(this.editRulesForm.menuArr);
        this.$refs.permissionTree.setCheckedKeys(
          this.editRulesForm.permissionArr
        );
      });
      // this.roleCreateIns.show()
    },
    // 重置表单
    resetForm() {
      this.$nextTick(() => {
        // this.$refs[formName].resetFields();
        if (this.$refs.editRulesForm !== undefined) {
          this.$refs.editRulesForm.resetFields();
        }
        this.editRulesForm = {
          role_name: undefined,
          role_memo: undefined,
          status: undefined,
          menuArr: [],
          permissionArr: [],
          menuArr_str: undefined,
          permissionArr_str: undefined
        };
      });
    },
    // 点击编辑
    handleUpdate(row) {
      this.dialogStatus = "update";
      this.row_id = row.role_id;
      this.dialogFormVisible = true;
      this.addEditVisible = true;
      let urlData = `?role_id=${row.role_id}`;
      // 另存菜单 和 权限

      // this.editRulesForm.menuArr = menu_str.split(',');
      // this.editRulesForm.permissionArr = permission_str.split(',')
      getRoleDetail(urlData).then(response => {
        this.editRulesForm.role_name = response.data.role_name;
        this.editRulesForm.role_memo = response.data.role_memo;
        this.editRulesForm.status = response.data.status;
        this.editRulesForm.menuArr_str = response.data.menu_arr;
        this.editRulesForm.permissionArr_str = response.data.permission_arr;
        this.editRulesForm.menuArr = response.data.menu_arr.split(",");
        this.editRulesForm.permissionArr = response.data.permission_arr.split(
          ","
        );
        this.addEditVisible = false;
      });
    },
    // 获取权限联动
    getPermissionArr() {
      getPermission().then(response => {
        // 遍历数组 item是每一个对象
        let arr = [];
        response.data.forEach(item => {
          // 遍历对象的属性 如果有children就接着遍历
          if (item["children"].length != 0) {
            let obj = JSON.parse(JSON.stringify(item));
            obj["children"] = [];
            item["children"].forEach(menu => {
              if (menu["children"].length != 0) {
                obj["children"].push(menu);
                return;
              }
            });
            if (obj["children"].length > 0) {
              arr.push(obj);
            }
          }
        });
        this.permissionList = arr;
      });
    },
    // 获取菜单联动
    getMenuArr() {
      getMenu().then(response => {
        this.menuArrList = response.data;
      });
    },
    // 点击全选 反选权限
    toggleCheckPermission() {
      if (!this.checkPermission) {
        // 全选
        this.$refs.permissionTree.setCheckedNodes(this.permissionList);
        this.checkPermission = !this.checkPermission;
        this.editRulesForm.permissionArr_str = this.getStr(
          this.$refs.permissionTree.getCheckedNodes(true, false)
        );
      } else {
        // 取消选中
        this.$refs.permissionTree.setCheckedKeys([]);
        this.checkPermission = !this.checkPermission;
        this.editRulesForm.permissionArr_str = this.getStr(
          this.$refs.permissionTree.getCheckedNodes(true, false)
        );
      }
    },
    // 点击全选 反选菜单
    toggleCheckMenu() {
      if (!this.checkMenu) {
        // 全选
        this.$refs.menuTree.setCheckedNodes(this.menuArrList);
        this.checkMenu = !this.checkMenu;
        this.editRulesForm.menuArr_str = this.getStr(
          this.$refs.menuTree.getCheckedNodes(false, true)
        );
      } else {
        // 取消选中
        this.$refs.menuTree.setCheckedKeys([]);
        this.checkMenu = !this.checkMenu;
        this.editRulesForm.menuArr_str = this.getStr(
          this.$refs.menuTree.getCheckedNodes(false, true)
        );
      }
    },
    // 点击权限列表
    handleCheckPermissionChange() {
      this.editRulesForm.permissionArr_str = this.getStr(
        this.$refs.permissionTree.getCheckedNodes(true, false)
      );
    },
    // 点击菜单列表
    handleCheckMenuChange() {
      this.editRulesForm.menuArr_str = this.getStr(
        this.$refs.menuTree.getCheckedNodes(false, true)
      );
    },
    // 将数组对象中的menu_id抽取出来拼接成字符串
    getStr(arr) {
      let str = "";
      arr.forEach(item => {
        for (let key in item) {
          if (key === "menu_id") {
            str += `${item[key]},`;
          }
        }
      });
      str = str.substring(0, str.length - 1);
      return str;
    },
    // 点击提交
    confirmSubmit(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (this.dialogStatus === "create") {
            let form = {};
            form.role_name = this.editRulesForm.role_name;
            form.role_memo = this.editRulesForm.role_memo;
            form.status = this.editRulesForm.status;
            form.menu_arr = this.editRulesForm.menuArr_str;
            form.permission_arr = this.editRulesForm.permissionArr_str;
            postAddData(form).then(response => {
              if (response.code === 200) {
                this.getList();
                this.dialogFormVisible = false;
                this.$notify({
                  type: "success",
                  message: "操作成功",
                  position: "bottom-right",
                  showClose: false,
                  duration: 3000
                });
              }
            });
          } else {
            let form = {};
            form.role_name = this.editRulesForm.role_name;
            form.role_memo = this.editRulesForm.role_memo;
            form.status = this.editRulesForm.status;
            form.menu_arr = this.editRulesForm.menuArr_str;
            form.permission_arr = this.editRulesForm.permissionArr_str;
            form.role_id = this.row_id;
            postEditData(form).then(response => {
              if (response.code === 200) {
                this.getList();
                this.dialogFormVisible = false;
                this.$notify({
                  type: "success",
                  message: "操作成功",
                  position: "bottom-right",
                  showClose: false,
                  duration: 3000
                });
              }
            });
          }
        } else {
          return false;
        }
      });
    },
    // 点击单个删除
    handleDelete(row) {
      this.dataIds = row.role_id;
      this.deleteDialogVisible = true;
    },

    // 确定删除
    confirmDelete() {
      deleteData(this.dataIds)
        .then(response => {
          if (response.code === 200) {
            this.getList();
            this.deleteDialogVisible = false;
            this.$notify({
              type: "success",
              message: "操作成功",
              position: "bottom-right",
              showClose: false,
              duration: 3000
            });
          }
        })
        .finally(() => {
          this.deleteDialogVisible = false;
        });
    }
  }
};
</script>

<style scoped>
[v-cloak] {
  display: none;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both;
}

.box-card {
  width: 100%;
}

.demo-form-inline {
  float: right;
}

/deep/ .el-card__header {
  padding-bottom: 0;
}
</style>
